import time

from qcloud_cos import CosConfig, CosS3Client, CosServiceError
from fastapi import HTTPException
from src.config import settings
from src.utils.logger import logger

# 全局变量，用于存储 COS 客户端实例
# 在 lifespan 中初始化，通过依赖注入传递
cos_client_instance: CosS3Client = None

def init_cos_client() -> CosS3Client:
    """
    初始化腾讯云 COS 客户端
    """
    global cos_client_instance
    
    if cos_client_instance is not None:
        return cos_client_instance

    try:
        # 验证必要的配置
        required_settings = {
            'COS_REGION': settings.COS_REGION,
            'COS_SECRET_ID': settings.COS_SECRET_ID,
            'COS_SECRET_KEY': settings.COS_SECRET_KEY,
            'COS_BUCKET_NAME': settings.COS_BUCKET_NAME
        }
        
        missing_settings = [key for key, value in required_settings.items() if not value]
        if missing_settings:
            raise ValueError(f"Missing required COS settings: {', '.join(missing_settings)}")

        logger.info("正在初始化 COS 客户端...")
        logger.info(f"Region: {settings.COS_REGION}")
        logger.info(f"Bucket: {settings.COS_BUCKET_NAME}")

        config = CosConfig(
            Region=settings.COS_REGION,
            SecretId=settings.COS_SECRET_ID,
            SecretKey=settings.COS_SECRET_KEY
        )
        
        cos_client_instance = CosS3Client(config)
        
        # 测试连接
        test_cos_connection()
        
        logger.info("COS 客户端初始化成功")
        return cos_client_instance

    except Exception as e:
        error_msg = f"初始化 COS 客户端失败: {str(e)}"
        logger.error(error_msg)
        raise RuntimeError(error_msg)

def get_cos_client() -> CosS3Client:
    """
    获取 COS 客户端实例
    """
    if cos_client_instance is None:
        raise RuntimeError("COS client not initialized")
    return cos_client_instance

def test_cos_connection() -> dict:
    """
    测试 COS 连接并返回详细信息
    """
    try:
        logger.info("正在测试 COS 连接...")
        response = cos_client_instance.list_objects(
            Bucket=settings.COS_BUCKET_NAME,
            MaxKeys=1
        )
        logger.info("COS 连接测试成功")
        return {
            "status": "success",
            "message": "Successfully connected to COS",
            "details": {
                "bucket": settings.COS_BUCKET_NAME,
                "region": settings.COS_REGION,
                "objects_count": response.get('Contents', [])
            }
        }
    except CosServiceError as e:
        error_msg = f"COS 服务错误: {e.get_error_code()} - {e.get_error_msg()}"
        logger.error(error_msg)
        return {
            "status": "error",
            "message": error_msg,
            "details": {
                "error_code": e.get_error_code(),
                "error_message": e.get_error_msg(),
                "request_id": e.get_request_id()
            }
        }
    except Exception as e:
        error_msg = f"测试 COS 连接时发生错误: {str(e)}"
        logger.error(error_msg)
        return {
            "status": "error",
            "message": error_msg,
            "details": {
                "error_type": type(e).__name__,
                "error_message": str(e)
            }
        } 